package cn.tfyhyc.springcloud.controller;

import cn.tfyhyc.springcloud.entities.CommonResult;
import cn.tfyhyc.springcloud.entities.Payment;
import cn.tfyhyc.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 头发又黑又长
 * @Date 2022/10/3 10:07
 * @email zwb15083976291@163.com
 */


/**
 * RestTemplate:
 */
@RestController
@Slf4j
@RequestMapping("/consumer")
public class OrderController {
    //    public static final String URL = "http://localhost:8001";
    public static final String URL = "http://CLOUD-PAYMENT-SERVICE"; // 使用的是EurekaServer中注册中心的服务名称

    @Resource
    private RestTemplate restTemplate;

    // 自己实现的负载均衡规则
    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(URL + "/payment/", payment, CommonResult.class);
    }

    @GetMapping("/payment/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(URL + "/payment/" + id, CommonResult.class);
    }

    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(URL + "/payment/" + id, CommonResult.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        }
        return new CommonResult<>(400, "操作失败");
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instances(instances); // 使用我们自己的负载均衡规则获取服务器实例
        return restTemplate.getForObject(instance.getUri() + "/payment/lb/loadBalancer", String.class);
    }

    // zipkin 测试
    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject(URL + "/payment/zipkin", String.class);
    }


}
